import express from 'express'
const router = express.Router();
import { loginService, updateAdminService, getCaptchaService } from '../service/userService';
import { formatResponse } from '../utils/tool';
import { ValidationError } from '../utils/errors';

/* GET users listing. */
router.post('/login', async function(req, res, next) {
  // 验证码不正确
  if (req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase()) {
    throw new ValidationError('验证码错误')
  }

  const result = await loginService(req.body)
  if (result.token) {
    res.setHeader('authentication', result.token)
  }
  // 统一返回格式
  res.send(formatResponse(0, "", result.data))
});

// 恢复登录状态
router.get('/whoami', async function(req, res, next) {
  res.send(formatResponse(0, "", req.auth))
})

// 修改用户信息
router.put('/', async function(req, res, next) {
  const updateInfo = await updateAdminService(req.body)
  res.send(formatResponse(0, '', updateInfo))
})

// 获取验证码
router.get('/captcha', async function(req, res, next) {
  // 生成一个验证码
  const captcha = await getCaptchaService()

  // 将 验证码存入 session 方便 登录时比较
  req.session.captcha = captcha.text
  console.log('captcha.text >>> ', captcha.text);
  res.setHeader('Content-Type', 'image/svg+xml')
  res.send(captcha.data)
});

export default router;
